package cate.game.status;

import cp.solution.util.time.TimeSpanCheck;
import cate.game.db.SaveConstants;
import cate.game.framework.ModuleMan;
import cate.game.util.IntervalCounter;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.data.domain.Sort;

import java.util.Date;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

public class GameStatusManager extends ModuleMan {
    public GameStatus data;

    @Override
    public void initDependent() throws Exception {
        List<GameStatus> list= game.facilities.getMongo().gameStatus.findAll(Sort.by("version").descending());
        data = CollectionUtils.isEmpty(list) ? null : list.get(0);
        if (data == null) {
            data = new GameStatus();
            data.version = 1;
            data.openTime = System.currentTimeMillis();
        }
        if(game.config.getOpenTime() > 0){
            //修正开服时间
            data.openTime = game.config.getOpenTime();
        }
        data.initialize();
    }

    @Override
    public synchronized void shutdown(){
        if(data != null){
            data.version++;
            data.id = null;
            data.saveTime = new Date();
            game.facilities.getMongo().gameStatus.insert(data);
        }
    }

    public long getOpenTime(){
        return data.openTime;
    }

    public int getOpenDay(){
        return data.getOpenDay(game);
    }

    public boolean checkDaySpan(){
        return 0 != data.lastDaySpanTime && TimeSpanCheck.spanDay(data.lastDaySpanTime);
    }

    public boolean checkWeekSpan(){
        return 0 != data.lastWeekSpanTime && TimeSpanCheck.spanWeek(data.lastWeekSpanTime);
    }

    public boolean checkMonthSpan(){
        return 0 != data.lastMonthSpanTime && TimeSpanCheck.spanMonth(data.lastMonthSpanTime);
    }

    @Override
    public void onDaySpan(){
        data.lastDaySpanTime = game.time.now();
    }

    @Override
    public void onWeekSpan(){
        data.lastWeekSpanTime = game.time.now();
    }

    @Override
    public void onMonthSpan(){
        data.lastMonthSpanTime = game.time.now();
    }

    private static final AtomicInteger IDX = new AtomicInteger(0);
    private IntervalCounter saveTrigger = new IntervalCounter(SaveConstants.STATUS_SAVE_SECONDS, IDX.getAndIncrement());

    public void tick(){
        if(saveTrigger.trigger()){
            long start = System.currentTimeMillis();
            shutdownSafe();
            log.debug("game status定时保存完成, cost{} ms", System.currentTimeMillis() - start);
        }
    }
}
